package 剑指offer;


/*
 * Author：江松
 * Date：2023/3/11 12:46
 *
 把数组排成最小的数：贪心，排序
 [3,32,321] ---321323

 思路1：依次比较每一位，位数值较小的排在前面(取模运算避免讨论)
 思路2：转换为字符串比较，x+y<y+x;
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Main19 {
    public String PrintMinNumber(int [] numbers) {
        if(numbers==null||numbers.length==0)return "";
        //升箱，转换
        Integer nums[]=Arrays.stream(numbers).boxed().toArray(Integer[]::new);
        Arrays.sort(nums, new Comparator<Integer>() {
            public ArrayList<Integer> getBits(Integer n){
                ArrayList<Integer>arr=new ArrayList<>();
                //个位到高位,高位放数组前边
                while(n>0){
                    arr.add(0,n%10);
                    n/=10;
                }
                return arr;
            }
            @Override
            public int compare(Integer o1, Integer o2) {
                ArrayList<Integer>arr1=getBits(o1);
                ArrayList<Integer>arr2=getBits(o2);
                int len1=arr1.size(),len2=arr2.size(),mlen=Math.max(len1,len2);
                int i=0;
                for(i=0;i<mlen;++i){
                    //使用取模运算来避免多种情况的讨论
                    int a1=arr1.get(i%len1),a2=arr2.get(i%len2);
                    if(a1==a2)continue;
                    else if(a1<a2){
                        return -1;
                    }else{
                        return 1;
                    }
                }
                return 0;
            }
        });
        StringBuilder sb=new StringBuilder();
        for(int i:nums){
            sb.append(i);
        }
        return sb.toString();
        }


    public String PrintMinNumber2(int [] numbers) {
        if(numbers==null||numbers.length==0)return "";
        String nums[]=new String[numbers.length];
        for(int i=0;i<numbers.length;++i){
            nums[i]=numbers[i]+"";
        }
        Arrays.sort(nums, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (o1+o2).compareTo(o2+o1);
            }
        });
        StringBuilder sb=new StringBuilder();
        for(String i:nums){
            sb.append(i);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        //int arr[]={3,32,321};
        int arr[]={3,11};
        System.out.println(new Main19().PrintMinNumber(arr));
    }
}
